<?php

namespace app\service;

//好友服务层
use app\enum\UserCode;
use app\model\FriendRequest;
use app\model\FriendShip;
use app\model\User;
use server\start_text_gateway;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;


class UserFriendService extends Base
{


    //获取陌生人列表
    public function stranger_list($user_id, $limit)
    {
        //排除已经是好友的用户
        $user_ship = FriendShip::where('user_id', $user_id)->column('friend_id');
        $list = User::field('id,nickname,avatar')->order('id', 'desc')->whereNotIn('id', $user_ship)->where('id', '<>', $user_id)->paginate($limit);
        return apiSuccess($list);
    }

    /**
     * 好友关系列表
     * @throws ModelNotFoundException
     * @throws DataNotFoundException
     * @throws DbException
     */
    public function ship_list($user_id, $limit)
    {
        $list = (new FriendShip())->where('user_id', $user_id)->with('friend')->paginate($limit);
        return apiSuccess($list);
    }

    //获取请求列表
    public function request_list($user_id, $limit)
    {
        $list = (new FriendRequest())->where('receiver_id', $user_id)->where('state', '=', UserCode::FRIEND_STATE['发起请求'])->order('state asc')->with('friend')->paginate($limit);
        return apiSuccess($list);
    }

    //搜索好友
    public function search($user_id, $keyword, $limit)
    {
        $list = User::field('id,nickname,avatar')->whereLike('nickname', '%' . $keyword . '%')->paginate($limit);

        foreach ($list->items() as &$item) {
            //是不是好友
            $item->is_friend = (new FriendShip())->where('user_id', $user_id)->where('friend_id', $item->id)->find() ? 1 : 0;

            //有没有已经发出申请
            if ($item->is_friend == 0) {
                $friend_request = (new FriendRequest())->where('sender_id', $user_id)->where('state', UserCode::FRIEND_STATE['发起请求'])->where('receiver_id', $item->id)->count();
                if ($friend_request) {
                    $item->is_friend = 2;
                }
            }
        }
        return apiSuccess($list);
    }

    //绑定好友亲密关系
    public function bind_ship($user_id, $friend_id, $answer)
    {
        $friend_user = User::where('id', $friend_id)->find();
        if (!$friend_user) {
            return apiError('用户不存在');
        }
        //检测是否已经是好友
        $friend_ship = FriendShip::where('user_id', $user_id)->where('friend_id', $friend_id)->find();
        if (!$friend_ship) {
            return apiError('不是好友,不能绑定亲密关系');
        }
        if ($friend_ship->status == UserCode::FRIEND_SHIP_STATUS['已绑定']) {
            return apiError('已经绑定过了');
        }

        if ($answer == $friend_user->answer) {
            //绑定好友关系
            $friend_ship->status = UserCode::FRIEND_SHIP_STATUS['已绑定'];
            $friend_ship->save();
            $my_ship = FriendShip::where('user_id', $friend_id)->where('friend_id', $user_id)->find();
            $my_ship->status = UserCode::FRIEND_SHIP_STATUS['已绑定'];
            $my_ship->save();
        } else {
            return apiError('问题验证失败');
        }

        return apiSuccess();
    }


    /**
     * 添加好友
     * @throws ModelNotFoundException
     * @throws DataNotFoundException
     * @throws DbException
     */
    public function add($user_id, $receiver_id, $remarks = '加个好友吧'): array
    {
        //创建一个好友请求
        $friend_request = (new FriendRequest())->where('sender_id', $user_id)->where('receiver_id', $receiver_id)->find();

        //好友关系是否存在
        $friend_ship = (new FriendShip())->where('user_id', $user_id)->where('friend_id', $receiver_id)->find();
        if ($friend_ship) {
            return apiError('已经是好友了');
        }

        if ($friend_request) {
            if ($friend_request->state == UserCode::FRIEND_STATE['已通过']) {
                return apiError('已经是好友了');
            }

            if ($friend_request->state == UserCode::FRIEND_STATE['发起请求']) {
                return apiError('已经发送过请求了');
            }
        }

        //检测$receiver_id 是否存在
        $user = (new User())->where('id', $receiver_id)->find();
        if (!$user) {
            return apiError('用户不存在');
        }

        //id不能是自己
        if ($user_id == $receiver_id) {
            return apiError('不能添加自己为好友');
        }


        //创建好友请求
        $friend_request = new FriendRequest();
        $friend_request->sender_id = $user_id;
        $friend_request->receiver_id = $receiver_id;
        $friend_request->state = UserCode::FRIEND_STATE['发起请求'];
        $friend_request->remarks = $remarks;

        $res = $friend_request->save();
        if (!$res) {
            return apiError('添加失败');
        } else {
            $this->push(UserCode::ADD_FRIEND, $friend_request->receiver_id, $user_id, '你有新的好友请求');
            return apiSuccess('请求已发送');
        }

    }


    //处理好友请求
    public function verify($user_id, $id, $state)
    {
        $friend_request = FriendRequest::where('receiver_id', $user_id)->where('id', $id)->find();
        if (!$friend_request) {
            return apiError('请求不存在');
        }

        //好友关系是否存在
        $friend_ship = FriendShip::where('user_id', $user_id)->where('friend_id', $friend_request->sender_id)->find();
        if ($friend_ship) {
            return apiError('已经是好友了');
        }

        if ($friend_request->state == UserCode::FRIEND_STATE['已通过']) {
            return apiError('已经是好友了');
        }

        if ($friend_request->state == UserCode::FRIEND_STATE['已拒绝']) {
            return apiError('已经拒绝过了');
        }

        if ($state == UserCode::FRIEND_STATE['已通过']) {
            $friend_request->state = UserCode::FRIEND_STATE['已通过'];
            $res = $friend_request->save();
            if (!$res) {
                return apiError('添加好友失败');
            } else {
                //创建好友关系
                $friend_ship = new FriendShip();
                $friend_ship->user_id = $friend_request->sender_id;
                $friend_ship->friend_id = $friend_request->receiver_id;
                $friend_ship->save();

                $friend_ship = new FriendShip();
                $friend_ship->user_id = $friend_request->receiver_id;
                $friend_ship->friend_id = $friend_request->sender_id;
                $friend_ship->save();


                //检测我是否也有好友请求发给他
                $friend_request_2 = (new FriendRequest())->where('receiver_id', $friend_request->sender_id)->where('sender_id', $user_id)->find();

                if ($friend_request_2) {
                    $friend_request_2->state = UserCode::FRIEND_STATE['已通过'];
                    $friend_request_2->save();
                }

                $this->push(UserCode::ADD_FRIEND_PASS, $friend_request->sender_id, $user_id, '对方已同意你的好友申请');
                return apiSuccess('添加好友成功');
            }
        }

        if ($state == UserCode::FRIEND_STATE['已拒绝']) {
            $friend_request->state = UserCode::FRIEND_STATE['已拒绝'];
            $res = $friend_request->save();
            if (!$res) {
                return apiError('拒绝失败');
            } else {
                $this->push(UserCode::ADD_FRIEND_REFUSE, $friend_request->sender_id, $user_id, '对方拒绝了你的好友申请');
                return apiSuccess('拒绝成功');
            }
        }
        return apiError('操作失败');
    }


    //消息推送
    protected function push($type, $friend_id, $source, $msg): void
    {
        $data = [
            'type' => $type,
            'data' => [
                'code' => 1,
                'msg' => $msg,
                'data' => [
                    'source' => $source,
                ]

            ]
        ];
        //判断是否在线
        if (start_text_gateway::isUidOnline($friend_id)) {
            var_dump('玩家在线' . $friend_id);
            start_text_gateway::sendToUid($friend_id, json_encode($data));
        }
    }


}